%--------------------------------------------------------------------------
% @author zhangwei on 20080101
% split large dataset into serveral small data
% 
% @input
%   g_raw_datafile     the orginal data file without any processing
%   g_segment_window   seconds 
%   g_sampling_rate    point/second
%   g_filecounter[out] how many file generated 
%--------------------------------------------------------------------------

clear all;
pack;
cd d:\dev\sciexplorer\source\experiment\eeg-24
cd d:\data\eeg-24

% g_raw_datafile = 'Pt1_DMA02_macro1-24_100Hz.mat';
% g_sample_rate = 100; % 100/sec
g_segment_window = 3600 % seconds
g_segment_sec = g_segment_window + 400; % another 400 sec patched to the segment
g_file_count = 1;

%--------------------------------------------------------------------------
disp( ['script spt_segment.m running...' ] );

if (length(whos('g_raw_datafile')) == 0)
    disp( ['error: undefined variable g_raw_datafile'] );
    return;
end
disp( ['input raw data file g_raw_datafile = ' g_raw_datafile ] );

mx_rawdata = load( g_raw_datafile );
g_sample_rate = mx_rawdata.ds_samp_freq;

%--------------------------------------------------------------------------
% assume each channel is represented as a row in the data file
% this is in accordance with the EEG recording data from Mayer

n_segment_length = g_segment_sec * g_sample_rate;
mx_size = size(mx_rawdata.data);
if (mx_size(1) > mx_size(2))
    error( 'the raw input data must be an long row first matrix' );
end

n_channel_count = mx_size(1);
n_total_length = mx_size(2);

g_file_count = 1; 
n_idx = 1;
while (n_idx < n_total_length)
    n_idxend = n_idx + g_segment_sec * g_sample_rate;
    n_idxend = min( n_idxend, n_total_length );
    mx_segment = mx_rawdata.data( :, n_idx:n_idxend );
    s_segfile = ['segment' num2str(g_file_count) '.mat'];
    save( s_segfile, 'mx_segment' );
    g_file_count = g_file_count + 1;
    n_idx = n_idx + g_segment_window * g_sample_rate;
    disp( ['-> ' s_segfile ' done.'] );
    pack;
end

% clear mx_segment;
% clear mx_rawdata;
pack;

cd D:\dev\sciexplorer\source\experiment\ecog-01(seg)
load segment1.mat
block = block.mx_segment;
save segment1.mat block;

for (I=1:24)
    segfile = ['segment' num2str(I) '.mat'];
    filedata = load( segfile );
    block = filedata.mx_segment;
    save( segfile, 'block' );
end
    
load segment



